<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>04马赛克</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}
			body {
				overflow: hidden;
			}
			#firCan {
				display: block;
				border: 1px solid khaki;
				margin: 20px auto;
			}
		</style>
	</head>
	<body>
		<canvas id="firCan" width="1000" height="625">
			您的浏览器版本过低, 不支持Canvas, 请升级!
		</canvas>
	</body>
	<script type="text/javascript">
		// 1, 获取Canvas
		var firCan = document.getElementById("firCan");
		// 2, 获取 2d渲染上下文
		var context = firCan.getContext('2d');
		// 3, 加载图片
		// 创建 img对象
		var imgObj = new Image();
		// 设置 src
		imgObj.src = "img/banner3.png";
		// 图片加载完毕
		imgObj.onload = function() {
			// 图片绘制到 canvas: drawImage()
			context.drawImage(imgObj, 0, 0, 1280, 800, 0, 0, 1000, 625);
			
			// 获取像素点
			var imageData = context.getImageData(0, 0, firCan.width, firCan.height);
			// 定义数组存储所有的颜色值
			var pixels = imageData.data;
			console.log(imageData);
			console.log(imageData.data);
			
			// 清除画布
			context.clearRect(0, 0, firCan.width, firCan.height);
			
			// 绘制网格
			var col = 50;
			var row = 25;
			var lRW = firCan.width / col;
			var lRH = firCan.height / row;
			
			// 绘制小矩形
			// 外层 for控制行数
			for (var i = 0; i < row; i++) {
				// 内层for控制列数
				for (var j = 0; j < col; j++) {
					// 找下标
					// 1, 先确定目标点前面有多少行
					var rows = Math.floor(lRH / 2) + i * lRH;
					// 2, 然后再乘以canvas的宽度, 得到多少个点
					var tPoint = rows * firCan.width;
					// 3, 再 确定目标点左侧有多少个点
					var lPoint = Math.floor(lRW / 2) + j * lRW;
					// 4, 计算下标
					var index = (tPoint + lPoint) * 4;
					// 加工颜色
					var r = pixels[index + 0];
					var g = pixels[index + 1];
					var b = pixels[index + 2];
					var color = "rgb(" + r + "," + g + "," + b + ")";
					// 设置填充颜色
					context.fillStyle = color;
					// 绘制矩形
					context.fillRect(j * lRW, i * lRH, lRW, lRH);
				}
			}
		}
		
		
		
	</script>
</html>
